// useScaleEffect.ts
import { onMounted, onUnmounted } from 'vue'
import { useEventListener, useTimeoutFn } from '@vueuse/core'
import { gsap } from 'gsap'

const duration = 0.3
let inst: GSAPTween | null = null
let inst2: GSAPTween | null = null
let pressTimeout: ReturnType<typeof useTimeoutFn> | null = null

const handlePressEvent = (event: MouseEvent | TouchEvent) => {
	const target = event.target as Element
	const element = target.closest('.app-bg-react,.app-text-react') as HTMLElement | null
	if (element) {
		inst?.kill()
		inst2?.kill()
		inst = gsap.to(element, {
			duration: duration / 2,
			scale: 0.95,
			onComplete: () => {
				inst2?.kill()
				inst2 = gsap.to(element, { duration: duration / 2, scale: 1 })
			}
		})

		pressTimeout = useTimeoutFn(() => inst?.pause(), (duration / 2) * 1000 - 10)
	}
}

const handleReleaseEvent = () => {
	pressTimeout?.stop()
	pressTimeout = null

	inst?.play()
	inst2?.kill()
}

export const useScaleEffect = () => {
	onMounted(() => {
		useEventListener(document, 'mousedown', handlePressEvent)
		useEventListener(document, 'mouseup', handleReleaseEvent)
		useEventListener(document, 'mouseleave', handleReleaseEvent)
		useEventListener(document, 'touchstart', handlePressEvent)
		useEventListener(document, 'touchend', handleReleaseEvent)
		useEventListener(document, 'touchcancel', handleReleaseEvent)
	})

	onUnmounted(() => {
		pressTimeout?.stop()
		pressTimeout = null
	})
}

export default useScaleEffect
